
#include "Image.h"


Image::Image(const std::string& name)
{
   // Give everything default values.
  strFilePath = name;
  image = 0;
  imageWidth = 0;
  imageHeight = 0;
}


Image::~Image()
{
   freeImage();
}


bool Image::loadBMP()
{
	FILE *pFile = 0;
	
	const char *file = strFilePath.c_str();
	
	// These will hold the bitmap header and file information.
	BITMAPINFOHEADER bitmapInfoHeader;
	BITMAPFILEHEADER header;

   // This will be used to swap the image colors from BGR to RGB.
	unsigned char textureColors = 0;

   // Open the file and make sure no errors.
	pFile = fopen(file, "rb");
	if(pFile == 0) return false;

	// Read in the bitmap header info into the BITMAPFILEHEADER variable.
	fread(&header, sizeof(BITMAPFILEHEADER), 1, pFile);
	
	// Make sure this is a real bitmap by checking the ID.
	if(header.bfType != BITMAP_ID)
	   {
		   fclose(pFile);
		   return false;
	   }

	// Read in the second header info into the BITMAPINFOHEADER variable.
	fread(&bitmapInfoHeader, sizeof(BITMAPINFOHEADER), 1, pFile);

	// Save the width and height.
   imageWidth = bitmapInfoHeader.biWidth;
   imageHeight = bitmapInfoHeader.biHeight;

   // Make sure we read a size out of it.
   if(bitmapInfoHeader.biSizeImage == 0)
      bitmapInfoHeader.biSizeImage = bitmapInfoHeader.biWidth *
      bitmapInfoHeader.biHeight * 3;

	// Place the pointer in front of where the image data starts.
	fseek(pFile, header.bfOffBits, SEEK_SET);

	// Dynamically create enough memory for the image.
	image = new unsigned char[bitmapInfoHeader.biSizeImage];

	// Error checking.  Make sure the memory was allocated.
	if(!image)
	   {
		   delete[] image;
		   fclose(pFile);
		   return false;
	   }

	// Read in the image.
	fread(image, 1, bitmapInfoHeader.biSizeImage, pFile);

	// Bitmaps are saved in BGR format so we will make the image RGB by...
	for(int index = 0; index < (int)bitmapInfoHeader.biSizeImage; index+=3)
	   {
		   textureColors = image[index];
		   image[index] = image[index + 2];
		   image[index + 2] = textureColors;
	   }

   // Close the file and return the image.
	fclose(pFile);
	return true;
}


void Image::freeImage()
{
   // When the application is done delete all dynamically allocated memory.
   if(image)
      {
         delete[] image;
         image = 0;
      }
}




